﻿using IronPython.Hosting;
using IronPython.Runtime;
using Microsoft.Scripting;
using Microsoft.Scripting.Hosting;
using System.Collections.Generic;

namespace ScriptingEngineModule
{
    class ScriptingEngine
    {
        private ScriptEngine pyEngine = null;
        private ScriptRuntime pyRuntime = null;
        private ScriptScope pyScope = null;
        private ScriptSource pySource = null;

        private GameModule module = null;

        public ScriptingEngine(GameModule module)
        {
            this.module = module;

            this.pyEngine = Python.CreateEngine();
            this.pyRuntime = pyEngine.Runtime;
            this.pyScope = pyRuntime.CreateScope();
        }

        private void loadScript(string script)
        {
            this.pySource = this.pyEngine.CreateScriptSourceFromFile(script, System.Text.Encoding.Default, SourceCodeKind.AutoDetect);
            this.pySource.Execute(this.pyScope);
        }

        private void loadScripts(List<string> scripts)
        {
            foreach (string script in scripts)
            {
                loadScript(script);
            }
        }

        public void runModule()
        {
            var pythonOps = pyEngine.Operations;
            //na chwile obecna rozumiem, ze jezeli skrypty pythonowe sa w jednym katalogu
            //nie musze ich w plikach .py importowac jezeli zostana odpowiednio wczytane 
            //z poziomu c# i zaladowane do kontekstu
            loadScript(module.RoundManager);
            loadScripts(module.Rounds);
            loadScripts(module.Turns);
            loadScripts(module.Moves);

            var pythonType = pyScope.GetVariable("RoundManager");
            

            //tworze instancje obiektu pythonowego
            dynamic instance = pythonOps.CreateInstance(pythonType, new object[0]);
            //uruchamiam dynamiczna metode
            instance.onGameStart();
        }
    }
}
